package com.jfinalnat.httpclient.sdk;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.message.BasicHeader;

public class CookieService {
	
	private String sessionIdKey = "JSESSIONID";
	
	public void CookieHandler(HttpRequest request) {
		
		if(PoolingHttpClientConfig.isEnable) {
			sessionIdKey = "morSeuritySessionID";
		}
		
		Header[] cookieHeaders = request.getHeaders("Cookie");
		request.removeHeaders("Cookie");
		for (int i = 0; i < cookieHeaders.length; i++) {
			String value = cookieHeaders[i].getValue();
			value = value.replace(sessionIdKey, "Jfinal-Client");
			value = value.replace("Jfinal-Nat=Jfinal-Client", sessionIdKey);
			request.addHeader(new BasicHeader(cookieHeaders[i].getName(), value));
		}
	}
	
	public void CookieFirstHandler(HttpRequest request) {
		
		if(PoolingHttpClientConfig.isEnable) {
			sessionIdKey = "morSeuritySessionID";
		}
		
		Header cookieHeader = request.getFirstHeader("Cookie");
		request.removeHeaders("Cookie");
		if (cookieHeader != null) {			
			String value = cookieHeader.getValue();
			value = value.replace(sessionIdKey, "Jfinal-Client");
			value = value.replace("Jfinal-Nat=Jfinal-Client", sessionIdKey);
			request.addHeader(new BasicHeader(cookieHeader.getName(), value));
		}
	}

}
